<?php
class Auth{
    protected $_config = array(
        'AUTH_ON'           => true,                      // 认证开关
        'AUTH_TYPE'         => 0,                         // 认证方式，1为实时认证；2为登录认证。
        'USER_ROLE'        => 'user_role',        // 用户组数据表名
        'USER' => 'user', // 用户-用户组关系表
        'USER_RULE'         => 'user_rule',         // 权限规则表
        'USER_INFO'         => ''             // 用户信息表
    );

    public function __construct() {
        // $prefix = C('DB_PREFIX');
        $prefix = '';
        $this->_config['USER_ROLE'] = $prefix.$this->_config['USER_ROLE'];
        $this->_config['USER_RULE'] = $prefix.$this->_config['USER_RULE'];
        $this->_config['USER'] = $prefix.$this->_config['USER'];
        // if (C('AUTH_CONFIG')) {
            //可设置配置项 AUTH_CONFIG, 此配置项为数组。
            // $this->_config = array_merge($this->_config, C('AUTH_CONFIG'));
        // }
    }

    /**
      * 检查权限
      * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
      * @param uid  int           认证用户的id
      * @param string mode        执行check的模式
      * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
      * @return boolean           通过验证返回true;失败返回false
     */
    public function check($name, $uid, $type=0, $mode='url', $relation='or') {
        if (!$this->_config['AUTH_ON'])
            return true;
        $authList = $this->getAuthList($uid,$type); //获取用户需要验证的所有有效规则列表
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = array($name);
            }
        }
        $list = array(); //保存验证通过的规则名
        if ($mode=='url') {
            $REQUEST = unserialize( strtolower(serialize($_REQUEST)) );
        }
        foreach ( $authList as $auth ) {
            $query = preg_replace('/^.+\?/U','',$auth);
            if ($mode=='url' && $query!=$auth ) {
                parse_str($query,$param); //解析规则中的param
                $intersect = array_intersect_assoc($REQUEST,$param);
                $auth = preg_replace('/\?.*$/U','',$auth);
                if ( in_array($auth,$name) && $intersect==$param ) {  //如果节点相符且url参数满足
                    $list[] = $auth ;
                }
            }else if (in_array($auth , $name)){
                $list[] = $auth ;
            }
        }
        if ($relation == 'or' and !empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ($relation == 'and' and empty($diff)) {
            return true;
        }
        return false;
    }
    public function getRole($uid) {
        static $groups = [];
        if (isset($groups[$uid])){
            return $groups[$uid];
        }else{
            $user_groups = Db::table($this->_config['USER'])->alias('u')
                         ->left([$this->_config['USER_ROLE'],'r'],'r.role_id = u.role_id')
                         ->where(['u.user_id=? and u.status = ?'=>[$uid,1]])
                         ->select();
        
            $groups[$uid] = $user_groups ? : array();
            return $groups[$uid];
        }
    }

    /**
     * 获得权限列表
     * @param integer $uid  用户id
     * @param integer $type 
     */
    public function getAuthList($uid,$type) {
        static $_authList = [];
        $t = implode(',',(array)$type);
        if (isset($_authList[$uid.$t])) {
            return $_authList[$uid.$t];
        }
        if( $this->_config['AUTH_TYPE']==2 && isset($_SESSION['_AUTH_LIST_'.$uid.$t])){
            return $_SESSION['_AUTH_LIST_'.$uid.$t];
        }

        //读取用户所属用户组
        $groups = $this->getRole($uid);
        $ids = [];//保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids,unserialize($g['role_rules']));
        }
        $ids = array_unique($ids);
        // var_dump($ids);
        if (empty($ids)) {
            $_authList[$uid.$t] = [];
        }
        $where = [
            'rule_id' => $ids,
            'rule_type' => $type,
            'rule_status' => 1
        ];
        $rules = Db::table($this->_config['USER_RULE'])
               ->field(['rule_condition','rule_name'])
               ->where($where)
               ->select();
        var_dump($rules);
        $authList = [];   //
        foreach ($rules as $rule) {
            if(empty($rule['rule_condition'])){
                $authList[] = strtolower($rule['rule_name']);
            }else{
                $authList[] = strtolower($rule['rule_condition']);
            }
        }
        var_dump($authList);
                
        $_authList[$uid.$t] = $authList;
        if($this->_config['AUTH_TYPE']==2){
            //规则列表结果保存到session
            $_SESSION['_AUTH_LIST_'.$uid.$t]=$authList;
        }
        return array_unique($authList);
    }

    /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    protected function getUserInfo($uid) {
        static $userinfo=array();
        if(!isset($userinfo[$uid])){
             // $userinfo[$uid]=M()->where(array('uid'=>$uid))->table($this->_config['AUTH_USER'])->find();
            $userinfo[$uid] = Db::table($this->_config['USER'])->where(['user_id'=>$uid])->one();
        }
        return $userinfo[$uid];
    }
    public function getRules($user_id){
        $roles = $this->getRole($uid);
        $ids = [];
        foreach ($roles as $role) {
            $ids = array_merge($ids,unserialize($role['role_rules']));
        }
        $ids = array_unique($ids);
        $where = [
            'rule_id' => $ids,
            'rule_status' => 1
        ];
        $rules = Db::table($this->_config['USER_RULE'])
               ->field(['rule_condition','rule_name'])
               ->where($where)
               ->select();
        $result = [];
        foreach ($rules as $rule) {
            if(empty($rule['rule_condition'])){
                $result[] = strtolower($rule['rule_name']);
            }else{
                $reuslt[] = strtolower($rule['rule_condition']);
            }
        }
        return $result;
        
    }
}
